<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="SpringBoot,TCP,Heartbeat," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言Netty 是一个高性能的 NIO 网络框架，本文基于 SpringBoot 以常见的心跳机制来认识 Netty。
最终能达到的效果：

客户端每隔 N 秒检测是否需要发送心跳。
服务端也每隔 N 秒检测是否需要发送心跳。
服务端可以主动 push 消息到客户端。
基于 SpringBoot 监控，可以查看实时连接以及各种应用信息。

效果如下：">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty(一) SpringBoot 整合长连接心跳机制">
<meta property="og:url" content="http://crossoverjie.top/2018/05/24/netty/Netty(1)TCP-Heartbeat/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言Netty 是一个高性能的 NIO 网络框架，本文基于 SpringBoot 以常见的心跳机制来认识 Netty。
最终能达到的效果：

客户端每隔 N 秒检测是否需要发送心跳。
服务端也每隔 N 秒检测是否需要发送心跳。
服务端可以主动 push 消息到客户端。
基于 SpringBoot 监控，可以查看实时连接以及各种应用信息。

效果如下：">
<meta property="og:image" content="https://i.loli.net/2018/05/25/5b0774828db53.jpeg">
<meta property="og:image" content="https://crossoverjie.top/uploads/netty-Heartbeat.gif">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d54648799.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d54fe2535.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d555538b7.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d569ca76a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d56d1fd2d.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6e3140db.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6e7c835b.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6ed19d78.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6f026a21.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6f5911b1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6fa3cec7.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d6fd37fb9.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d7009a4ef.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d704eb0a6.jpg">
<meta property="og:updated_time" content="2019-05-07T19:06:29.221Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Netty(一) SpringBoot 整合长连接心跳机制">
<meta name="twitter:description" content="前言Netty 是一个高性能的 NIO 网络框架，本文基于 SpringBoot 以常见的心跳机制来认识 Netty。
最终能达到的效果：

客户端每隔 N 秒检测是否需要发送心跳。
服务端也每隔 N 秒检测是否需要发送心跳。
服务端可以主动 push 消息到客户端。
基于 SpringBoot 监控，可以查看实时连接以及各种应用信息。

效果如下：">
<meta name="twitter:image" content="https://i.loli.net/2018/05/25/5b0774828db53.jpeg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/05/24/netty/Netty(1)TCP-Heartbeat/"/>

  <title> Netty(一) SpringBoot 整合长连接心跳机制 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Netty(一) SpringBoot 整合长连接心跳机制
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-05-24T01:02:54+08:00" content="2018-05-24">
              2018-05-24
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Netty/" itemprop="url" rel="index">
                    <span itemprop="name">Netty</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/05/24/netty/Netty(1)TCP-Heartbeat/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/05/24/netty/Netty(1)TCP-Heartbeat/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/05/24/netty/Netty(1)TCP-Heartbeat/" class="leancloud_visitors" data-flag-title="Netty(一) SpringBoot 整合长连接心跳机制">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2018/05/25/5b0774828db53.jpeg" alt="photo-1522204657746-fccce0824cfd.jpeg"></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>Netty 是一个高性能的 NIO 网络框架，本文基于 SpringBoot 以常见的心跳机制来认识 Netty。</p>
<p>最终能达到的效果：</p>
<ul>
<li>客户端每隔 N 秒检测是否需要发送心跳。</li>
<li>服务端也每隔 N 秒检测是否需要发送心跳。</li>
<li>服务端可以主动 push 消息到客户端。</li>
<li>基于 SpringBoot 监控，可以查看实时连接以及各种应用信息。</li>
</ul>
<p>效果如下：</p>
<p><img src="https://crossoverjie.top/uploads/netty-Heartbeat.gif" alt="show"></p>
<a id="more"></a>
<h1 id="IdleStateHandler"><a href="#IdleStateHandler" class="headerlink" title="IdleStateHandler"></a>IdleStateHandler</h1><p>Netty 可以使用 IdleStateHandler 来实现连接管理，当连接空闲时间太长（没有发送、接收消息）时则会触发一个事件，我们便可在该事件中实现心跳机制。</p>
<h2 id="客户端心跳"><a href="#客户端心跳" class="headerlink" title="客户端心跳"></a>客户端心跳</h2><p>当客户端空闲了 N 秒没有给服务端发送消息时会自动发送一个心跳来维持连接。</p>
<p>核心代码代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EchoClientHandle</span> <span class="keyword">extends</span> <span class="title">SimpleChannelInboundHandler</span>&lt;<span class="title">ByteBuf</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Logger LOGGER = LoggerFactory.getLogger(EchoClientHandle.class);</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">userEventTriggered</span><span class="params">(ChannelHandlerContext ctx, Object evt)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (evt <span class="keyword">instanceof</span> IdleStateEvent)&#123;</div><div class="line">            IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;</div><div class="line"></div><div class="line">            <span class="keyword">if</span> (idleStateEvent.state() == IdleState.WRITER_IDLE)&#123;</div><div class="line">                LOGGER.info(<span class="string">"已经 10 秒没有发送信息！"</span>);</div><div class="line">                <span class="comment">//向服务端发送消息</span></div><div class="line">                CustomProtocol heartBeat = SpringBeanFactory.getBean(<span class="string">"heartBeat"</span>, CustomProtocol.class);</div><div class="line">                ctx.writeAndFlush(heartBeat).addListener(ChannelFutureListener.CLOSE_ON_FAILURE) ;</div><div class="line">            &#125;</div><div class="line"></div><div class="line"></div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">super</span>.userEventTriggered(ctx, evt);</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">channelRead0</span><span class="params">(ChannelHandlerContext channelHandlerContext, ByteBuf in)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        <span class="comment">//从服务端收到消息时被调用</span></div><div class="line">        LOGGER.info(<span class="string">"客户端收到消息=&#123;&#125;"</span>,in.toString(CharsetUtil.UTF_8)) ;</div><div class="line"></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>实现非常简单，只需要在事件回调中发送一个消息即可。</p>
<p>由于整合了 SpringBoot ，所以发送的心跳信息是一个单例的 Bean。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartBeatConfig</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;channel.id&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> <span class="keyword">long</span> id ;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Bean</span>(value = <span class="string">"heartBeat"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> CustomProtocol <span class="title">heartBeat</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> CustomProtocol(id,<span class="string">"ping"</span>) ;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里涉及到了自定义协议的内容，请继续查看下文。</p>
<p>当然少不了启动引导：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Component</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartbeatClient</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Logger LOGGER = LoggerFactory.getLogger(HeartbeatClient.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> EventLoopGroup group = <span class="keyword">new</span> NioEventLoopGroup();</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;netty.server.port&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> nettyPort;</div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;netty.server.host&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> String host;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> SocketChannel channel;</div><div class="line"></div><div class="line">    <span class="meta">@PostConstruct</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">        Bootstrap bootstrap = <span class="keyword">new</span> Bootstrap();</div><div class="line">        bootstrap.group(group)</div><div class="line">                .channel(NioSocketChannel.class)</div><div class="line">                .handler(<span class="keyword">new</span> CustomerHandleInitializer())</div><div class="line">        ;</div><div class="line"></div><div class="line">        ChannelFuture future = bootstrap.connect(host, nettyPort).sync();</div><div class="line">        <span class="keyword">if</span> (future.isSuccess()) &#123;</div><div class="line">            LOGGER.info(<span class="string">"启动 Netty 成功"</span>);</div><div class="line">        &#125;</div><div class="line">        channel = (SocketChannel) future.channel();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomerHandleInitializer</span> <span class="keyword">extends</span> <span class="title">ChannelInitializer</span>&lt;<span class="title">Channel</span>&gt; </span>&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(Channel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        ch.pipeline()</div><div class="line">                <span class="comment">//10 秒没发送消息 将IdleStateHandler 添加到 ChannelPipeline 中</span></div><div class="line">                .addLast(<span class="keyword">new</span> IdleStateHandler(<span class="number">0</span>, <span class="number">10</span>, <span class="number">0</span>))</div><div class="line">                .addLast(<span class="keyword">new</span> HeartbeatEncode())</div><div class="line">                .addLast(<span class="keyword">new</span> EchoClientHandle())</div><div class="line">        ;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>所以当应用启动每隔 10 秒会检测是否发送过消息，不然就会发送心跳信息。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d54648799.jpg" alt=""></p>
<h2 id="服务端心跳"><a href="#服务端心跳" class="headerlink" title="服务端心跳"></a>服务端心跳</h2><p>服务器端的心跳其实也是类似，也需要在 ChannelPipeline 中添加一个 IdleStateHandler 。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartBeatSimpleHandle</span> <span class="keyword">extends</span> <span class="title">SimpleChannelInboundHandler</span>&lt;<span class="title">CustomProtocol</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Logger LOGGER = LoggerFactory.getLogger(HeartBeatSimpleHandle.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ByteBuf HEART_BEAT =  Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(<span class="keyword">new</span> CustomProtocol(<span class="number">123456L</span>,<span class="string">"pong"</span>).toString(),CharsetUtil.UTF_8));</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 取消绑定</div><div class="line">     * <span class="doctag">@param</span> ctx</div><div class="line">     * <span class="doctag">@throws</span> Exception</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelInactive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        NettySocketHolder.remove((NioSocketChannel) ctx.channel());</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">userEventTriggered</span><span class="params">(ChannelHandlerContext ctx, Object evt)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (evt <span class="keyword">instanceof</span> IdleStateEvent)&#123;</div><div class="line">            IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;</div><div class="line"></div><div class="line">            <span class="keyword">if</span> (idleStateEvent.state() == IdleState.READER_IDLE)&#123;</div><div class="line">                LOGGER.info(<span class="string">"已经5秒没有收到信息！"</span>);</div><div class="line">                <span class="comment">//向客户端发送消息</span></div><div class="line">                ctx.writeAndFlush(HEART_BEAT).addListener(ChannelFutureListener.CLOSE_ON_FAILURE) ;</div><div class="line">            &#125;</div><div class="line"></div><div class="line"></div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">super</span>.userEventTriggered(ctx, evt);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">channelRead0</span><span class="params">(ChannelHandlerContext ctx, CustomProtocol customProtocol)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        LOGGER.info(<span class="string">"收到customProtocol=&#123;&#125;"</span>, customProtocol);</div><div class="line"></div><div class="line">        <span class="comment">//保存客户端与 Channel 之间的关系</span></div><div class="line">        NettySocketHolder.put(customProtocol.getId(),(NioSocketChannel)ctx.channel()) ;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>这里有点需要注意</strong>：</p>
<p>当有多个客户端连上来时，服务端需要区分开，不然响应消息就会发生混乱。</p>
<p>所以每当有个连接上来的时候，我们都将当前的 Channel 与连上的客户端 ID 进行关联（<strong>因此每个连上的客户端 ID 都必须唯一</strong>）。</p>
<p>这里采用了一个 Map 来保存这个关系，并且在断开连接时自动取消这个关联。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NettySocketHolder</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Map&lt;Long, NioSocketChannel&gt; MAP = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;(<span class="number">16</span>);</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">put</span><span class="params">(Long id, NioSocketChannel socketChannel)</span> </span>&#123;</div><div class="line">        MAP.put(id, socketChannel);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> NioSocketChannel <span class="title">get</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> MAP.get(id);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Map&lt;Long, NioSocketChannel&gt; <span class="title">getMAP</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> MAP;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">(NioSocketChannel nioSocketChannel)</span> </span>&#123;</div><div class="line">        MAP.entrySet().stream().filter(entry -&gt; entry.getValue() == nioSocketChannel).forEach(entry -&gt; MAP.remove(entry.getKey()));</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>启动引导程序：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div></pre></td><td class="code"><pre><div class="line">Component</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartBeatServer</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Logger LOGGER = LoggerFactory.getLogger(HeartBeatServer.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> EventLoopGroup boss = <span class="keyword">new</span> NioEventLoopGroup();</div><div class="line">    <span class="keyword">private</span> EventLoopGroup work = <span class="keyword">new</span> NioEventLoopGroup();</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;netty.server.port&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> nettyPort;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 启动 Netty</div><div class="line">     *</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     * <span class="doctag">@throws</span> InterruptedException</div><div class="line">     */</div><div class="line">    <span class="meta">@PostConstruct</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line"></div><div class="line">        ServerBootstrap bootstrap = <span class="keyword">new</span> ServerBootstrap()</div><div class="line">                .group(boss, work)</div><div class="line">                .channel(NioServerSocketChannel.class)</div><div class="line">                .localAddress(<span class="keyword">new</span> InetSocketAddress(nettyPort))</div><div class="line">                <span class="comment">//保持长连接</span></div><div class="line">                .childOption(ChannelOption.SO_KEEPALIVE, <span class="keyword">true</span>)</div><div class="line">                .childHandler(<span class="keyword">new</span> HeartbeatInitializer());</div><div class="line"></div><div class="line">        ChannelFuture future = bootstrap.bind().sync();</div><div class="line">        <span class="keyword">if</span> (future.isSuccess()) &#123;</div><div class="line">            LOGGER.info(<span class="string">"启动 Netty 成功"</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 销毁</div><div class="line">     */</div><div class="line">    <span class="meta">@PreDestroy</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</div><div class="line">        boss.shutdownGracefully().syncUninterruptibly();</div><div class="line">        work.shutdownGracefully().syncUninterruptibly();</div><div class="line">        LOGGER.info(<span class="string">"关闭 Netty 成功"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;    </div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartbeatInitializer</span> <span class="keyword">extends</span> <span class="title">ChannelInitializer</span>&lt;<span class="title">Channel</span>&gt; </span>&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(Channel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        ch.pipeline()</div><div class="line">                <span class="comment">//五秒没有收到消息 将IdleStateHandler 添加到 ChannelPipeline 中</span></div><div class="line">                .addLast(<span class="keyword">new</span> IdleStateHandler(<span class="number">5</span>, <span class="number">0</span>, <span class="number">0</span>))</div><div class="line">                .addLast(<span class="keyword">new</span> HeartbeatDecoder())</div><div class="line">                .addLast(<span class="keyword">new</span> HeartBeatSimpleHandle());</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>也是同样将IdleStateHandler 添加到 ChannelPipeline 中，也会有一个定时任务，每5秒校验一次是否有收到消息，否则就主动发送一次请求。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d54fe2535.jpg" alt=""></p>
<p>因为测试是有两个客户端连上所以有两个日志。</p>
<h2 id="自定义协议"><a href="#自定义协议" class="headerlink" title="自定义协议"></a>自定义协议</h2><p>上文其实都看到了：服务端与客户端采用的是自定义的 POJO 进行通讯的。</p>
<p>所以需要在客户端进行编码，服务端进行解码，也都只需要各自实现一个编解码器即可。</p>
<p>CustomProtocol：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomProtocol</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">4671171056588401542L</span>;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">long</span> id ;</div><div class="line">    <span class="keyword">private</span> String content ;</div><div class="line">    <span class="comment">//省略 getter/setter</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>客户端的编码器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartbeatEncode</span> <span class="keyword">extends</span> <span class="title">MessageToByteEncoder</span>&lt;<span class="title">CustomProtocol</span>&gt; </span>&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">encode</span><span class="params">(ChannelHandlerContext ctx, CustomProtocol msg, ByteBuf out)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        out.writeLong(msg.getId()) ;</div><div class="line">        out.writeBytes(msg.getContent().getBytes()) ;</div><div class="line"></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>也就是说消息的前八个字节为 header，剩余的全是 content。</p>
<p>服务端的解码器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeartbeatDecoder</span> <span class="keyword">extends</span> <span class="title">ByteToMessageDecoder</span> </span>&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        <span class="keyword">long</span> id = in.readLong() ;</div><div class="line">        <span class="keyword">byte</span>[] bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[in.readableBytes()] ;</div><div class="line">        in.readBytes(bytes) ;</div><div class="line">        String content = <span class="keyword">new</span> String(bytes) ;</div><div class="line"></div><div class="line">        CustomProtocol customProtocol = <span class="keyword">new</span> CustomProtocol() ;</div><div class="line">        customProtocol.setId(id);</div><div class="line">        customProtocol.setContent(content) ;</div><div class="line">        out.add(customProtocol) ;</div><div class="line"></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>只需要按照刚才的规则进行解码即可。</p>
<h2 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h2><p>其实联想到 IdleStateHandler 的功能，自然也能想到它实现的原理：</p>
<blockquote>
<p>应该会存在一个定时任务的线程去处理这些消息。</p>
</blockquote>
<p>来看看它的源码：</p>
<p>首先是构造函数:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">public IdleStateHandler(</div><div class="line">        int readerIdleTimeSeconds,</div><div class="line">        int writerIdleTimeSeconds,</div><div class="line">        int allIdleTimeSeconds) &#123;</div><div class="line"></div><div class="line">    this(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,</div><div class="line">         TimeUnit.SECONDS);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其实就是初始化了几个数据：</p>
<ul>
<li>readerIdleTimeSeconds：一段时间内没有数据读取</li>
<li>writerIdleTimeSeconds：一段时间内没有数据发送</li>
<li>allIdleTimeSeconds：以上两种满足其中一个即可</li>
</ul>
<p>因为 IdleStateHandler 也是一种 ChannelHandler，所以会在 <code>channelActive</code> 中初始化任务：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    <span class="comment">// This method will be invoked only if this handler was added</span></div><div class="line">    <span class="comment">// before channelActive() event is fired.  If a user adds this handler</span></div><div class="line">    <span class="comment">// after the channelActive() event, initialize() will be called by beforeAdd().</span></div><div class="line">    initialize(ctx);</div><div class="line">    <span class="keyword">super</span>.channelActive(ctx);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initialize</span><span class="params">(ChannelHandlerContext ctx)</span> </span>&#123;</div><div class="line">    <span class="comment">// Avoid the case where destroy() is called before scheduling timeouts.</span></div><div class="line">    <span class="comment">// See: https://github.com/netty/netty/issues/143</span></div><div class="line">    <span class="keyword">switch</span> (state) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="number">1</span>:</div><div class="line">    <span class="keyword">case</span> <span class="number">2</span>:</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    state = <span class="number">1</span>;</div><div class="line">    initOutputChanged(ctx);</div><div class="line"></div><div class="line">    lastReadTime = lastWriteTime = ticksInNanos();</div><div class="line">    <span class="keyword">if</span> (readerIdleTimeNanos &gt; <span class="number">0</span>) &#123;</div><div class="line">        readerIdleTimeout = schedule(ctx, <span class="keyword">new</span> ReaderIdleTimeoutTask(ctx),</div><div class="line">                readerIdleTimeNanos, TimeUnit.NANOSECONDS);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (writerIdleTimeNanos &gt; <span class="number">0</span>) &#123;</div><div class="line">        writerIdleTimeout = schedule(ctx, <span class="keyword">new</span> WriterIdleTimeoutTask(ctx),</div><div class="line">                writerIdleTimeNanos, TimeUnit.NANOSECONDS);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (allIdleTimeNanos &gt; <span class="number">0</span>) &#123;</div><div class="line">        allIdleTimeout = schedule(ctx, <span class="keyword">new</span> AllIdleTimeoutTask(ctx),</div><div class="line">                allIdleTimeNanos, TimeUnit.NANOSECONDS);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>也就是会按照我们给定的时间初始化出定时任务。</p>
<p>接着在任务真正执行时进行判断：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ReaderIdleTimeoutTask</span> <span class="keyword">extends</span> <span class="title">AbstractIdleTask</span> </span>&#123;</div><div class="line"></div><div class="line">    ReaderIdleTimeoutTask(ChannelHandlerContext ctx) &#123;</div><div class="line">        <span class="keyword">super</span>(ctx);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(ChannelHandlerContext ctx)</span> </span>&#123;</div><div class="line">        <span class="keyword">long</span> nextDelay = readerIdleTimeNanos;</div><div class="line">        <span class="keyword">if</span> (!reading) &#123;</div><div class="line">            nextDelay -= ticksInNanos() - lastReadTime;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (nextDelay &lt;= <span class="number">0</span>) &#123;</div><div class="line">            <span class="comment">// Reader is idle - set a new timeout and notify the callback.</span></div><div class="line">            readerIdleTimeout = schedule(ctx, <span class="keyword">this</span>, readerIdleTimeNanos, TimeUnit.NANOSECONDS);</div><div class="line"></div><div class="line">            <span class="keyword">boolean</span> first = firstReaderIdleEvent;</div><div class="line">            firstReaderIdleEvent = <span class="keyword">false</span>;</div><div class="line"></div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                IdleStateEvent event = newIdleStateEvent(IdleState.READER_IDLE, first);</div><div class="line">                channelIdle(ctx, event);</div><div class="line">            &#125; <span class="keyword">catch</span> (Throwable t) &#123;</div><div class="line">                ctx.fireExceptionCaught(t);</div><div class="line">            &#125;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="comment">// Read occurred before the timeout - set a new timeout with shorter delay.</span></div><div class="line">            readerIdleTimeout = schedule(ctx, <span class="keyword">this</span>, nextDelay, TimeUnit.NANOSECONDS);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如果满足条件则会生成一个 IdleStateEvent 事件。</p>
<h1 id="SpringBoot-监控"><a href="#SpringBoot-监控" class="headerlink" title="SpringBoot 监控"></a>SpringBoot 监控</h1><p>由于整合了 SpringBoot 之后不但可以利用 Spring 帮我们管理对象，也可以利用它来做应用监控。</p>
<h2 id="actuator-监控"><a href="#actuator-监控" class="headerlink" title="actuator 监控"></a>actuator 监控</h2><p>当我们为引入了:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-actuator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure>
<p>就开启了 SpringBoot 的 actuator 监控功能，他可以暴露出很多监控端点供我们使用。</p>
<p>如一些应用中的一些统计数据：<br><img src="https://i.loli.net/2019/05/08/5cd1d555538b7.jpg" alt=""></p>
<p>存在的 Beans：<br><img src="https://i.loli.net/2019/05/08/5cd1d569ca76a.jpg" alt=""></p>
<p>更多信息请查看：<a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html" target="_blank" rel="external">https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html</a></p>
<p>但是如果我想监控现在我的服务端有多少客户端连上来了，分别的 ID 是多少？</p>
<p>其实就是实时查看我内部定义的那个关联关系的 Map。</p>
<p>这就需要暴露自定义端点了。</p>
<h2 id="自定义端点"><a href="#自定义端点" class="headerlink" title="自定义端点"></a>自定义端点</h2><p>暴露的方式也很简单：</p>
<p>继承 AbstractEndpoint 并复写其中的 invoke 函数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomEndpoint</span> <span class="keyword">extends</span> <span class="title">AbstractEndpoint</span>&lt;<span class="title">Map</span>&lt;<span class="title">Long</span>,<span class="title">NioSocketChannel</span>&gt;&gt; </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 监控端点的 访问地址</div><div class="line">     * <span class="doctag">@param</span> id</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CustomEndpoint</span><span class="params">(String id)</span> </span>&#123;</div><div class="line">        <span class="comment">//false 表示不是敏感端点</span></div><div class="line">        <span class="keyword">super</span>(id, <span class="keyword">false</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> Map&lt;Long, NioSocketChannel&gt; <span class="title">invoke</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> NettySocketHolder.getMAP();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其实就是返回了 Map 中的数据。</p>
<p>再配置一个该类型的 Bean 即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EndPointConfig</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;monitor.channel.map.key&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> String channelMap;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function"><span class="keyword">public</span> CustomEndpoint <span class="title">buildEndPoint</span><span class="params">()</span></span>&#123;</div><div class="line">        CustomEndpoint customEndpoint = <span class="keyword">new</span> CustomEndpoint(channelMap) ;</div><div class="line">        <span class="keyword">return</span> customEndpoint ;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样我们就可以通过配置文件中的 <code>monitor.channel.map.key</code> 来访问了：</p>
<p>一个客户端连接时：<br><img src="https://i.loli.net/2019/05/08/5cd1d56d1fd2d.jpg" alt=""></p>
<p>两个客户端连接时：<br><img src="https://i.loli.net/2019/05/08/5cd1d6e3140db.jpg" alt=""></p>
<h2 id="整合-SBA"><a href="#整合-SBA" class="headerlink" title="整合 SBA"></a>整合 SBA</h2><p>这样其实监控功能已经可以满足了，但能不能展示的更美观、并且多个应用也可以方便查看呢？</p>
<p>有这样的开源工具帮我们做到了：</p>
<p><a href="https://github.com/codecentric/spring-boot-admin" target="_blank" rel="external">https://github.com/codecentric/spring-boot-admin</a></p>
<p>简单来说我们可以利用该工具将 actuator 暴露出来的接口可视化并聚合的展示在页面中：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d6e7c835b.jpg" alt=""></p>
<p>接入也很简单，首先需要引入依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>de.codecentric<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-admin-starter-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure>
<p>并在配置文件中加入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"># 关闭健康检查权限</div><div class="line">management.security.enabled=false</div><div class="line"># SpringAdmin 地址</div><div class="line">spring.boot.admin.url=http://127.0.0.1:8888</div></pre></td></tr></table></figure>
<p>在启动应用之前先讲 SpringBootAdmin 部署好：</p>
<p>这个应用就是一个纯粹的 SpringBoot ，只需要在主函数上加入 <code>@EnableAdminServer</code> 注解。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@SpringBootApplication</span></div><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="meta">@EnableAutoConfiguration</span></div><div class="line"><span class="meta">@EnableAdminServer</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AdminApplication</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		SpringApplication.run(AdminApplication.class, args);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>引入：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>de.codecentric<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-admin-starter-server<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.5.7<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>de.codecentric<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-admin-server-ui<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.5.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure>
<p>之后直接启动就行了。</p>
<p>这样我们在 SpringBootAdmin 的页面中就可以查看很多应用信息了。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d6ed19d78.jpg" alt=""></p>
<p>更多内容请参考官方指南：</p>
<p><a href="http://codecentric.github.io/spring-boot-admin/1.5.6/" target="_blank" rel="external">http://codecentric.github.io/spring-boot-admin/1.5.6/</a></p>
<h3 id="自定义监控数据"><a href="#自定义监控数据" class="headerlink" title="自定义监控数据"></a>自定义监控数据</h3><p>其实我们完全可以借助 actuator 以及这个可视化页面帮我们监控一些简单的度量信息。</p>
<p>比如我在客户端和服务端中写了两个 Rest 接口用于向对方发送消息。</p>
<p>只是想要记录分别发送了多少次：</p>
<p>客户端：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Controller</span></div><div class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IndexController</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 统计 service</div><div class="line">     */</div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> CounterService counterService;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> HeartbeatClient heartbeatClient ;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 向服务端发消息</div><div class="line">     * <span class="doctag">@param</span> sendMsgReqVO</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="meta">@ApiOperation</span>(<span class="string">"客户端发送消息"</span>)</div><div class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"sendMsg"</span>)</div><div class="line">    <span class="meta">@ResponseBody</span></div><div class="line">    <span class="function"><span class="keyword">public</span> BaseResponse&lt;SendMsgResVO&gt; <span class="title">sendMsg</span><span class="params">(@RequestBody SendMsgReqVO sendMsgReqVO)</span></span>&#123;</div><div class="line">        BaseResponse&lt;SendMsgResVO&gt; res = <span class="keyword">new</span> BaseResponse();</div><div class="line">        heartbeatClient.sendMsg(<span class="keyword">new</span> CustomProtocol(sendMsgReqVO.getId(),sendMsgReqVO.getMsg())) ;</div><div class="line"></div><div class="line">        <span class="comment">// 利用 actuator 来自增</span></div><div class="line">        counterService.increment(Constants.COUNTER_CLIENT_PUSH_COUNT);</div><div class="line"></div><div class="line">        SendMsgResVO sendMsgResVO = <span class="keyword">new</span> SendMsgResVO() ;</div><div class="line">        sendMsgResVO.setMsg(<span class="string">"OK"</span>) ;</div><div class="line">        res.setCode(StatusEnum.SUCCESS.getCode()) ;</div><div class="line">        res.setMessage(StatusEnum.SUCCESS.getMessage()) ;</div><div class="line">        res.setDataBody(sendMsgResVO) ;</div><div class="line">        <span class="keyword">return</span> res ;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>只要我们引入了 actuator 的包，那就可以直接注入 counterService ，利用它来帮我们记录数据。</p>
<p>当我们调用该接口时：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d6f026a21.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d6f5911b1.jpg" alt=""></p>
<p>在监控页面中可以查询刚才的调用情况：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d6fa3cec7.jpg" alt=""></p>
<p>服务端主动 push 消息也是类似，只是需要在发送时候根据客户端的 ID 查询到具体的 Channel 发送：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d6fd37fb9.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d7009a4ef.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d704eb0a6.jpg" alt=""></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>以上就是一个简单 Netty 心跳示例，并演示了 SpringBoot 的监控，之后会继续更新 Netty 相关内容，欢迎关注及指正。</p>
<p>本文所有代码：</p>
<p><a href="https://github.com/crossoverJie/netty-action" target="_blank" rel="external">https://github.com/crossoverJie/netty-action</a></p>
<h1 id="号外"><a href="#号外" class="headerlink" title="号外"></a>号外</h1><p>最近在总结一些 Java 相关的知识点，感兴趣的朋友可以一起维护。</p>
<blockquote>
<p>地址: <a href="https://github.com/crossoverJie/Java-Interview" target="_blank" rel="external">https://github.com/crossoverJie/Java-Interview</a></p>
</blockquote>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SpringBoot/" rel="tag">#SpringBoot</a>
          
            <a href="/tags/TCP/" rel="tag">#TCP</a>
          
            <a href="/tags/Heartbeat/" rel="tag">#Heartbeat</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/15/skill/1Kstar/" rel="next" title="1K star+ 的项目是如何炼成的？">
                <i class="fa fa-chevron-left"></i> 1K star+ 的项目是如何炼成的？
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/06/exam/2018-06-07-The-university-entrance-exam/" rel="prev" title="记于 2018 年高考！">
                记于 2018 年高考！ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#IdleStateHandler"><span class="nav-number">2.</span> <span class="nav-text">IdleStateHandler</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端心跳"><span class="nav-number">2.1.</span> <span class="nav-text">客户端心跳</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端心跳"><span class="nav-number">2.2.</span> <span class="nav-text">服务端心跳</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义协议"><span class="nav-number">2.3.</span> <span class="nav-text">自定义协议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现原理"><span class="nav-number">2.4.</span> <span class="nav-text">实现原理</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#SpringBoot-监控"><span class="nav-number">3.</span> <span class="nav-text">SpringBoot 监控</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#actuator-监控"><span class="nav-number">3.1.</span> <span class="nav-text">actuator 监控</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义端点"><span class="nav-number">3.2.</span> <span class="nav-text">自定义端点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#整合-SBA"><span class="nav-number">3.3.</span> <span class="nav-text">整合 SBA</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义监控数据"><span class="nav-number">3.3.1.</span> <span class="nav-text">自定义监控数据</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#号外"><span class="nav-number">5.</span> <span class="nav-text">号外</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/05/24/netty/Netty(1)TCP-Heartbeat/';
      var disqus_title = "Netty(一) SpringBoot 整合长连接心跳机制";
      var disqus_url = 'http://crossoverjie.top/2018/05/24/netty/Netty(1)TCP-Heartbeat/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
